﻿namespace Enterprises.Wpf.Core.Net
{
    /// <summary>
    /// Modbus-Tcp协议支持的消息解析类
    /// </summary>
    public class ModbusTcpMessage : NetMessageBase, INetMessage
    {
        /// <inheritdoc cref="P:HslCommunication.Core.IMessage.INetMessage.ProtocolHeadBytesLength" />
        public int ProtocolHeadBytesLength => 8;

        /// <summary>
        /// 获取或设置是否进行检查返回的消息ID和发送的消息ID是否一致，默认为true，也就是检查<br />
        /// Get or set whether to check whether the returned message ID is consistent with the sent message ID, the default is true, that is, check
        /// </summary>
        public bool IsCheckMessageId { get; set; } = true;


        /// <inheritdoc cref="M:HslCommunication.Core.IMessage.INetMessage.GetContentLengthByHeadBytes" />
        public int GetContentLengthByHeadBytes()
        {
            if (base.HeadBytes?.Length >= ProtocolHeadBytesLength)
            {
                int num = base.HeadBytes[4] * 256 + base.HeadBytes[5];
                if (num == 0)
                {
                    byte[] array = new byte[ProtocolHeadBytesLength - 1];
                    for (int i = 0; i < array.Length; i++)
                    {
                        array[i] = base.HeadBytes[i + 1];
                    }
                    base.HeadBytes = array;
                    return base.HeadBytes[5] * 256 + base.HeadBytes[6] - 1;
                }
                return Math.Min(num - 2, 300);
            }
            return 0;
        }

        /// <inheritdoc cref="M:HslCommunication.Core.IMessage.INetMessage.CheckHeadBytesLegal(System.Byte[])" />
        public override bool CheckHeadBytesLegal(byte[] token)
        {
            if (IsCheckMessageId)
            {
                if (base.HeadBytes == null)
                {
                    return false;
                }
                if (base.SendBytes[0] != base.HeadBytes[0] || base.SendBytes[1] != base.HeadBytes[1])
                {
                    return false;
                }
                return base.HeadBytes[2] == 0 && base.HeadBytes[3] == 0;
            }
            return true;
        }

        /// <inheritdoc cref="M:HslCommunication.Core.IMessage.INetMessage.GetHeadBytesIdentity" />
        public override int GetHeadBytesIdentity()
        {
            return base.HeadBytes[0] * 256 + base.HeadBytes[1];
        }
    }

}
